import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import Register from '@/views/Register/index.vue'
import Index from '@/views/home/index.vue'
import UserList from '@/components/system/UserList/index.vue'
import RoleSelect from '@/components/system/RoleSelect/index.vue'
import PermissionSelect from '@/components/system/PermissionSelect/index.vue'
import DeviceList from '@/components/device/DeviceList/index.vue'
import Alarm from '@/components/device/Alarm/index.vue'
import More from '@/components/device/More/index.vue'
import Visualization from '@/views/Visualization/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: '登录',
      component: Login,
    },
    {
      path: '/',
      redirect: '/login', // 默认重定向到登录页面
    },
    {
      path: '/home',
      name: '首页',
      component: Index,
      meta: { title: '首页', requiresAuth: true },
      children: [
        {
          path: '/UserList',
          name: '用户列表',
          component: UserList,
          // meta: { title: '系统管理 / 用户管理' },
        },
        {
          path: '/RoleSelect',
          name: '角色列表',
          component: RoleSelect,
          // meta: { title: '系统管理 / 角色列表' },
        },
        {
          path: '/PermissionSelect',
          name: '菜单管理',
          component: PermissionSelect,
          // meta: { title: '系统管理 / 菜单管理' },
        },
        {
          path: '/DeviceList',
          name: '我的设备',
          component: DeviceList,
          // meta: { title: '设备管理 / 我的设备' },
        },
        {
          path: '/Alarm',
          name: '告警管理',
          component: Alarm,
          meta: { title: '设备管理 / 传感参数' },
        },
        {
          path: '/More',
          name: '更多操作',
          component: More,
          // meta: { title: '设备管理 / 更多操作' },
        },
      ],
    },
    {
      path: '/Visualization',
      name: '可视化大屏',
      component: Visualization,
    },
    {
      path: '/Register',
      name: '注册',
      component: Register,
    },
  ],
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') // 从 localStorage 获取 token

  // 如果路由需要登录且用户未登录
  if (to.meta.requiresAuth && !token) {
    ElMessage.warning('请先登录')
    return next('/login') // 跳转到登录页面
  }

  // 如果用户已登录且访问的是登录页面，跳转到首页
  if (to.path === '/login' && token) {
    return next('/Visualization')
  }

  next() // 继续导航
})

export default router
